package com.smbms.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.smbms.dao.UserMapper;
import com.smbms.pojo.Bill;
import com.smbms.pojo.User;
import com.smbms.service.UserService;
import com.smbms.util.PageParams;
import com.smbms.util.PageResult;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.Duration;
import java.util.List;

/**
 * 类名：UserServiceImpl
 * 作者：小涛
 * 创建时间：2021/9/8-16:16
 * 功能：
 */
@Service
public class UserServiceImpl implements UserService {

    @Resource
    private UserMapper userMapper;
    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    //加密接口
    BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();

    @Override
    public User getByLogin(User user) {
        User loginUser = userMapper.getByLogin(user);
        if (encoder.matches(user.getUserPassword(), loginUser.getUserPassword())){
            return loginUser;
        }
        return null;
    }

    @Override
    public PageResult<User> findPage(PageParams pageParams) {
        //判断缓存
        String key = "user:findPage:" + pageParams.getUserName() + ":" + pageParams.getUserRole() + ":" + pageParams.getGender()
                + ":" + pageParams.getPage() + ":" + pageParams.getSize();
        if (redisTemplate.hasKey(key)) {
            return (PageResult<User>) redisTemplate.opsForValue().get(key);
        }

        PageHelper.startPage(pageParams.getPage(), pageParams.getSize());
        //查询列表
        Page<User> page = userMapper.listParams(pageParams);

        long total = page.getTotal();
        List<User> result = page.getResult();
        PageResult<User> pageResult = new PageResult<>(page.getTotal(), page.getResult());
        redisTemplate.opsForValue().set(key, pageResult, Duration.ofHours(6));
        return pageResult;
    }

    @Transactional
    @Override
    public int delUser(Integer id) {
        return userMapper.delUser(id);
    }

    @Override
    public int checkCodeAdd(User user) {
        return userMapper.checkCodeAdd(user);
    }

    @Transactional
    @Override
    public int addUser(User user) {
        user.setUserPassword(encoder.encode(user.getUserPassword()));
        return userMapper.addUser(user);
    }

    @Override
    public User findById(Integer id) {
        return userMapper.findById(id);
    }

    @Override
    public int countByCodeUpd(String userCode, String self) {
        return userMapper.countByCodeUpd(userCode, self);
    }

    @Override
    public int updUser(User user) {
        user.setUserPassword(encoder.encode(user.getUserPassword()));
        return userMapper.updUser(user);
    }
}
